package main.java.responsibilitychain;

import main.java.responsibilitychain.filterobj.CheckFirstFilterObject;
import main.java.responsibilitychain.filterobj.CheckSecondFilterObject;

import java.util.LinkedList;
import java.util.List;

/**
 * @author xin麒
 * @date 2023/2/3 11:18
 */
public class ResponsibilityChainPattern {
    private List<MyAbstractHandler> abstractHandlerList;
    private MyAbstractHandler abstractHandler;

    private void initAbstractHandlerList() {//有2点需要优化
        //1、初始化abstractHandlerList，最好用反射来注入
        //2、 排序的话可能要写一个注解或者设置一些字段来标注顺序标识order,
        // 在1的注入完毕基础上对顺序标识对过滤节点进行排序或者拿到order，对order排序在初始化abstractHandlerList
        abstractHandlerList = new LinkedList<>();
        abstractHandlerList.add(new CheckFirstFilterObject());
        abstractHandlerList.add(new CheckSecondFilterObject());
    }

    private void initializeChainFilter() {//初始化abstractHandler
        if (abstractHandlerList == null) return;
        for (int i = 0; i < abstractHandlerList.size(); i++) {
            if (i == 0) {
                abstractHandler = abstractHandlerList.get(0);
            } else {
                abstractHandlerList.get(i - 1).setNextHandler(abstractHandlerList.get(i));
            }
        }
    }

    public ResponsibilityChainPattern() {//初始化，本来依靠反射来会好一些
        initAbstractHandlerList();//初始化
        initializeChainFilter();
    }

    public MyResponse exec(MyRequest myRequest, MyResponse myResponse) {
        if (abstractHandler != null) abstractHandler.filter(myRequest, myResponse);
        return myResponse;
    }
}
